package timer

import (
	"encoding/json"
	"fmt"
	"reflect"
)

func (g *TimerManager) addTimerFromStore(recordTimer *recordTimer) error {
	registry := g.timerRegistry[recordTimer.TimerType]
	if registry == nil {
		return fmt.Errorf("timer not registered %+v", recordTimer)
	}
	var data interface{}
	if registry.RType != nil {
		newValue := reflect.New(registry.RType)
		err := json.Unmarshal(recordTimer.Data, newValue.Interface())
		if err != nil {
			return err
		}
		data = newValue.Elem().Interface()
	}
	g.AddTimer(recordTimer.Key, recordTimer.TimerType, recordTimer.Delay, data)
	return nil
}

func (g *TimerManager) triggerTimer(timer *runtimeTimer) {
	g.RemoveTimer(timer.Key)
	registry := g.timerRegistry[timer.TimerType]
	if registry == nil {
		g.Errorf(timer.Key, "timer not registered %+v", timer)
		return
	}
	registry.HandlerFunc(timer.Data)
}
